#pragma once

#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/ximgproc.hpp>
#include <optional>
#include <unordered_map>
#include <string_view>
#include <filesystem>
#include <chrono>
#include <execution>
#include <algorithm>
#include <memory>
#include <vector>
#include <tuple>

namespace wire_detection {

/**
 * @brief 检测配置结构体，使用 C++17 强类型特性
 */
struct DetectionConfig {
    // 图像预处理参数
    int resize_height = 800;
    int blur_kernel_size = 3;
    int denoise_strength = 10;
    
    // 纹理复杂度分析参数
    int texture_window_size = 15;
    double texture_threshold = 0.15;
    int lbp_radius = 3;
    int lbp_n_points = 24;
    
    // 边缘检测参数
    int canny_low_threshold = 30;
    int canny_high_threshold = 80;
    int edge_dilation_kernel = 3;
    
    // 线条检测参数
    int hough_threshold = 20;
    int min_line_length = 10;
    int max_line_gap = 5;
    
    // Gabor 滤波器参数
    std::vector<double> gabor_frequencies{0.1, 0.3, 0.5};
    std::vector<double> gabor_angles{0, 45, 90, 135};
    
    // 判决参数
    double wire_density_threshold = 0.3;
    double texture_ratio_threshold = 2.0;
    double min_wire_area_ratio = 0.1;
    
    // 置信度权重
    struct ConfidenceWeights {
        double texture = 0.4;
        double edge_density = 0.3;
        double line_count = 0.2;
        double gabor_response = 0.1;
    } confidence_weights;
};

/**
 * @brief 检测结果结构体，使用现代 C++ 特性
 */
struct DetectionResult {
    bool has_wire = false;
    double confidence_score = 0.0;
    int conditions_met = 0;
    double texture_ratio = 0.0;
    double edge_density = 0.0;
    double line_density = 0.0;
    double direction_entropy = 0.0;
    std::size_t line_count = 0;
    double gabor_max_response = 0.0;
    double lbp_uniformity = 0.0;
    
    // 元数据
    std::filesystem::path image_path;
    cv::Size image_size;
    std::chrono::duration<double> processing_time;
    
    // 归一化特征
    struct NormalizedFeatures {
        double texture = 0.0;
        double edge_density = 0.0;
        double line_count = 0.0;
        double gabor_response = 0.0;
    } normalized_features;
    
    // 错误信息（使用 std::optional）
    std::optional<std::string> error_message;
};

/**
 * @brief 纹理分析结果
 */
struct TextureAnalysis {
    cv::Mat texture_map;
    cv::Mat high_texture_mask;
    double texture_ratio;
    double lbp_uniformity;
    double mean_texture_complexity;
};

/**
 * @brief 边缘分析结果
 */
struct EdgeAnalysis {
    cv::Mat edges;
    cv::Mat edges_dilated;
    double edge_density;
    cv::Mat edge_magnitude;
    double direction_entropy;
};

/**
 * @brief Gabor 分析结果
 */
struct GaborAnalysis {
    double max_response;
    double response_variance;
    std::vector<cv::mat id="A3QJpjJKsaFDyTgGP8slRBgDgqf"> all_responses;
};

/**
 * @brief 优化的铁丝检测器 C++17 实现
 * 
 * 这个类使用现代 C++17 特性重新实现了 Python 版本的所有功能，
 * 提供了更好的性能和类型安全保障。
 */
class OptimizedWireDetector {
public:
    /**
     * @brief 构造函数，使用移动语义优化
     */
    explicit OptimizedWireDetector(DetectionConfig config = {});
    
    /**
     * @brief 检测图像中的铁丝缠绕
     * @param image_path 图像文件路径
     * @return 检测结果，使用 std::optional 处理错误
     */
    [[nodiscard]] std::optional<detectionresult id="U6kHpk8WUaiYVog1tvtlD5HagSh"> detect_wire(
        const std::filesystem::path& image_path) const;
    
    /**
     * @brief 检测 OpenCV Mat 对象中的铁丝缠绕
     * @param image OpenCV 图像矩阵
     * @param image_path 可选的图像路径（用于结果记录）
     * @return 检测结果
     */
    [[nodiscard]] std::optional<detectionresult id="ZTZxpirXZaMAHdga8Mel3eaCg6f"> detect_wire(
        const cv::Mat& image, 
        const std::optional<std::filesystem::path id="XTNpp5AdLaCwQKgncYPlHsQKgDO">& image_path = std::nullopt) const;
    
    /**
     * @brief 批量检测多张图像
     * @param image_paths 图像路径向量
     * @return 检测结果映射
     */
    [[nodiscard]] std::unordered_map<std::string, detectionresult="" id="GsaCp9KHeaw2k3gsYcFl7sLVgyf"> 
    batch_detect(const std::vector<std::filesystem::path id="KiP5phSlaa5YSCgb6tJlOuxCgkc">& image_paths) const;
    
    /**
     * @brief 可视化检测过程
     * @param image_path 输入图像路径
     * @param save_path 可选的保存路径
     * @return 可视化结果图像
     */
    [[nodiscard]] std::optional<cv::mat id="FrSmpXQW4a60zMgCNKxlzLpIgPf"> visualize_detection(
        const std::filesystem::path& image_path,
        const std::optional<std::filesystem::path id="QBRspTl7kayyESghlb3lpm6lgDd">& save_path = std::nullopt) const;
    
    /**
     * @brief 更新配置，使用完美转发
     */
    template<typename configtype="" id="V7o5p6e4fauYihg5C40leI8fg9f">
    void update_config(ConfigType&& new_config) {
        config_ = std::forward<configtype id="P5PxpTPJpaDlHmggzPNlh06tgUh">(new_config);
    }
    
    /**
     * @brief 获取当前配置（只读）
     */
    [[nodiscard]] const DetectionConfig& get_config() const noexcept {
        return config_;
    }

private:
    DetectionConfig config_;
    
    // 核心算法实现
    [[nodiscard]] cv::Mat preprocess_image(const cv::Mat& image) const;
    [[nodiscard]] TextureAnalysis analyze_texture_complexity(const cv::Mat& image) const;
    [[nodiscard]] EdgeAnalysis detect_edge_features(const cv::Mat& image) const;
    [[nodiscard]] std::vector<cv::vec4i id="C8bJpqvfcaAEOIgZGwTlODQUgjf"> detect_lines_hough(const cv::Mat& edges) const;
    [[nodiscard]] GaborAnalysis analyze_gabor_response(const cv::Mat& image) const;
    [[nodiscard]] DetectionResult make_decision(
        const TextureAnalysis& texture,
        const EdgeAnalysis& edges, 
        const std::vector<cv::vec4i id="Ew3RpDaEcaPtI9gPGy2lcyW5gag">& lines,
        const GaborAnalysis& gabor,
        const cv::Size& original_size) const;
    
    // 辅助函数
    [[nodiscard]] cv::Mat apply_gabor_filter(
        const cv::Mat& image, double frequency, double angle) const;
    [[nodiscard]] double calculate_lbp_uniformity(const cv::Mat& image) const;
    [[nodiscard]] double calculate_direction_entropy(
        const cv::Mat& edge_magnitude, const cv::Mat& edge_direction) const;
    
    // 并行处理辅助函数
    template<typename container,="" typename="" function="" id="Oz3mpFGRqaUEmHgMQeClfybbgMd">
    void parallel_for_each(Container&& container, Function&& func) const {
        if constexpr (std::is_same_v<std::decay_t<container id="TFOepo7Jha1rH0gBx3LlV4tggKh">, std::vector<std::filesystem::path id="StlkpW8hXaxuDrgRweolvaRIgje">>) {
            std::for_each(std::execution::par_unseq, 
                         container.begin(), container.end(), 
                         std::forward<function id="HPLmphfLaaBRsPg9vuZlbvq8gBd">(func));
        } else {
            std::for_each(container.begin(), container.end(), 
                         std::forward<function id="ZbJeprakcalW89gFvQilXwUKgWf">(func));
        }
    }
};

/**
 * @brief 工厂函数：创建高敏感度检测器
 */
[[nodiscard]] std::unique_ptr<optimizedwiredetector id="PcuJp45QQa1aA6ggLwdliJs4gag"> 
create_high_sensitivity_detector();

/**
 * @brief 工厂函数：创建平衡检测器
 */
[[nodiscard]] std::unique_ptr<optimizedwiredetector id="DTCXpTPh5a32eTgD8Iilah80g0g"> 
create_balanced_detector();

/**
 * @brief 工厂函数：创建严格检测器
 */
[[nodiscard]] std::unique_ptr<optimizedwiredetector id="RkmIpvZo0a1iusgZsV7lVgtsgVh"> 
create_strict_detector();

} // namespace wire_detection</optimizedwiredetector></optimizedwiredetector></optimizedwiredetector></function></function></std::filesystem::path></std::decay_t<container></typename></cv::vec4i></cv::vec4i></configtype></typename></std::filesystem::path></cv::mat></std::filesystem::path></std::string,></std::filesystem::path></detectionresult></detectionresult></cv::mat></std::string></double></double></double></tuple></vector></memory></algorithm></execution></chrono></filesystem></string_view></unordered_map></optional></opencv2></opencv2>